/**
 * 
 */
package vin.echo.core;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import vin.echo.core.request.Protocol;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

/**
 * 
 * @author Vin.Ma
 * 
 */
public abstract class EchoService {

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	protected String sessionId;

	public EchoService() {
		
	}

	public EchoService(HttpServletRequest request,
			HttpServletResponse response) {

		this.setRequest(request);
		this.setResponse(response);
	}
	
	public void initService(){
		sessionId = (String) this.request.getSession().getAttribute(Protocol.SESSION_KEY);
	}

	public void echo(Object object) {
		try {
			response.setCharacterEncoding("utf-8");
			request.setCharacterEncoding("utf-8");
			if (object instanceof String) {
				response.getWriter().write(object.toString());
			} else {
				Gson gson = new GsonBuilder().create();
				String string = gson.toJson(object);

				response.getWriter().write(string);

			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void echo(InputStream inputStream) {
		BufferedInputStream inStream = new BufferedInputStream(inputStream);
		byte[] buffer = new byte[512];
		try {
			int flag = inStream.read(buffer);
			while (flag != -1) {
				response.getOutputStream().write(buffer);
				inputStream.read(buffer);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}
	
	public String encode(String msg) throws UnsupportedEncodingException{
		return new String(msg.getBytes(),"utf-8");
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

}
